package com.pro01.apirednote.aop;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;


@Component
@RequiredArgsConstructor
public class PerformanceMetricsCollector {

    private final MeterRegistry meterRegistry;

    private final ConcurrentHashMap<String, Timer> timers = new ConcurrentHashMap<>();
    

    public void recordExecutionTime(String uri, String method, long executionTime) {
        String metricName = "api.request.duration";
        String timerKey = metricName + "." + uri + "." + method;

        Timer timer = timers.computeIfAbsent(timerKey, key -> 
            Timer.builder(metricName)
                .tag("uri", uri)
                .tag("method", method)
                .description("API请求执行时间")
                .register(meterRegistry)
        );

        timer.record(executionTime, TimeUnit.MILLISECONDS);
    }
    

    public void incrementRequestCount(String uri, String method, int status) {
        meterRegistry.counter("api.request.count", 
                "uri", uri, 
                "method", method, 
                "status", String.valueOf(status))
                .increment();
    }
    

    public void incrementExceptionCount(String uri, String method, String exceptionClass) {
        meterRegistry.counter("api.request.exceptions", 
                "uri", uri, 
                "method", method, 
                "exception", exceptionClass)
                .increment();
    }
} 